<?php
/**
 * Created by PhpStorm.
 * User: caoguangyang
 * Date: 2021-06-27
 * Time: 9:21
 */
namespace App\Http\Controllers\Wx;

use App\CodeResponse;
use App\Http\Controllers\Controller;
use App\Notifications\VerificationCode;
use App\Services\User\UserServices;
use Carbon\Carbon;
use Faker\Provider\PhoneNumber;
use function foo\func;
use Illuminate\Http\Request;
use App\Models\User\User;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Leonis\Notifications\EasySms\Channels\EasySmsChannel;
use Overtrue\EasySms\EasySms;

class AuthController extends WxController
{
    private $userService;
    protected $only = ['info', 'profile'];

    public function __construct()
    {
        parent::__construct();
        $this->userService = UserServices::getInstance();
    }

    // 获取用户信息
    public function info() {
        $user = Auth::guard("wx")->user();
        return $this->success([
            'nickName' => $user->nickname,
            'avatar' => $user->avatar,
            'gender' => $user->gender,
            'mobile' => $user->mobile
        ]);
    }

    // 退出登录
    public function logout() {
        Auth::guard("wx")->logout();
        return $this->success();
    }

    //验证函数，获取登录用户
//    public function user() {
//        $user = Auth::guard("wx")->user();
//        return $this->success($user);
//    }

    /**
     * 注册
     * @param Request $request
     * @return array
     */
    public function register(Request $request)
    {
        //获取参数
        $username = $request->input('username');
        $password = $request->input('password');
        $mobile = $request->input('mobile');
        $code = $request->input('code');

        //验证数据是否为空
        if (empty($username) || empty($password) || empty($mobile) || empty($code)) {
            $this->fail(CodeResponse::PARAM_VALUE_ILLEGAL);
        }

        //验证验证码是否正确
        $this->userService->checkCaptcha($mobile,$code);

        //验证手机号格式
        $validator = Validator::make(['mobile'=>$mobile],['mobile'=>'regex:/^1[0-9]{10}$/']);
        if($validator->fails()){
            $this->fail(CodeResponse::AUTH_INVALID_MOBILE);
        }

        //验证用户名是否存在
        $user = $this->userService->getByUsername($username);
        if (!is_null($user)) {
            $this->fail(CodeResponse::AUTH_NAME_REGISTERED);
        }

        //验证手机号是否存在
        $user = $this->userService->getByUsername($mobile);
        if (!is_null($user)) {
            $this->fail(CodeResponse::AUTH_MOBILE_REGISTERED);
        }

        //写入用户表
        $user = new User();
        $user->username = $username;
        $user->password = Hash::make($password);
        $user->mobile = $mobile;
        $user->avatar = "https://yanxuan.nosdn.127.net/80839423d73d7e0qderh.jpg";
        $user->nickname = $username;
        $user->last_login_time = Carbon::now()->toDateTimeString();
        $user->last_login_ip = $request->getClientIP();
        $user->save();

        //新用户发券 TODO

        //生成token TODO
        $token = Auth::guard('wx')->login($user);

        //返回用户信息和token
        $data = [
            'token' => $token,
            'userInfo' => [
                "nickName" => $username,
                "avatarUrl" => $user->avatar
            ]
        ];
        return $this->success($data);
    }

    /**
     * 生成短信验证码
     * @param Request $request
     * @return mixed
     */
    public function regCaptcha(Request $request) {
        //获取手机号
        $mobile = $request->input("mobile");

        //验证手机是否为空
        if (empty($mobile)) {
            $this->fail(CodeResponse::PARAM_ILLEGAL);
        }

        //验证手机号合法性
        $validator = Validator::make(['mobile'=>$mobile],['mobile'=>'regex:/^1[0-9]{10}$/']);
        if($validator->fails()){
            $this->fail(CodeResponse::AUTH_INVALID_MOBILE);
        }

        //验证手机号是否被注册
        $user = $this->userService->getByUsername($mobile);
        if (!is_null($user)) {
            $this->fail(CodeResponse::AUTH_MOBILE_REGISTERED);
        }

        //生成六位验证码


        //防刷限制，超过一分钟可以点击发送，add如果存在返回false，说明数据已经被设置，而且未过期
        $lock = Cache::add('register_captcha_lock_'.$mobile,1,60);
        if (!$lock) {
            $this->fail(CodeResponse::AUTH_CAPTCHA_FREQUENCY);
        }

        //防刷限制：一天请求十次
        $isPass = $this->userService->checkMobileSendCaptchaCount($mobile);
        if(!$isPass){
            $this->fail(CodeResponse::AUTH_CAPTCHA_COUNT);
        }

        $code = $this->userService->setCaptcha($mobile);

        //发送短信
        //Notification::route(EasySmsChannel::class,new PhoneNumber($mobile,86))->notify(new VerificationCode($code));

        return ['errno' => 0, 'errmsg' => '成功', 'data' => null];
    }

    /**
     * 登录
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request) {
        //获取信息
        $username = $request->input('username');
        $password = $request->input('password');

        //验证数据
        if (empty($username) || empty($password)) {
            return $this->fail(CodeResponse::PARAM_VALUE_ILLEGAL);
        }

        //判断用户名和密码
        $user = $this->userService->getByUsername($username);
        if (is_null($user)) {
            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT);
        }

        $isPass = $isPass = Hash::check($password,$user->getAuthPassword());
        if (!$isPass) {
            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT,'账号密码不对');
        }

        //更新登录信息
        $user->last_login_time = now()->toDateTimeString();
        $user->last_login_ip = $request->getClientIp();
        if (!$user->save()) {
            return $this->fail(CodeResponse::UPDATED_FAIL);
        }

        //获取token,组装数据并返回
        $token = Auth::guard('wx')->login($user);
        return $this->success([
            'token' => $token,
            'userInfo' => [
                'nickName' => $username,
                'avatarUrl' => $user->avatar,
            ]
        ]);
    }

    /**
     * 重置密码
     * @param Request $request
     * @return mixed
     */
    public function reset(Request $request) {
        // 接收数据
        $password = $request->input("password");
        $mobile = $request->input("mobile");
        $code = $request->input("code");

        // 数据不能为空
        if (empty($password) || empty($mobile) || empty($code)) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }

        // 判断验证码是否正确
        $isPass = UserServices::getInstance()->checkCaptcha($mobile,$code);
        if (!$isPass) {
            return $this->fail(CodeResponse::AUTH_CAPTCHA_UNMATCH);
        }

        // 判断手机号是否存在
        $user = UserServices::getInstance()->getByMobile($mobile);
        if (is_null($user)) {
            return $this->fail(CodeResponse::AUTH_MOBILE_UNREGISTERED);
        }

        // 密码加密，更新
        $user->password = Hash::make($password);
        $ret = $user->save();
        return $this->failOrSuccess($ret, CodeResponse::UPDATED_FAIL);
    }

    /**
     * 用户信息修改
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function profile(Request $request) {
        // 接收数据
        $user = $this->user();
        $avatar = $request->input("avatar");
        $gender = $request->input("gender");
        $nickname = $request->input("nickname");

        // 更新数据
        if (!empty($avatar)) {
            $user->avatar = $avatar;
        }
        if (!empty($gender)) {
            $user->gender = $gender;
        }
        if (!empty($nickname)) {
            $user->nickname = $nickname;
        }

        $ret = $user->save();
        return $this->failOrSuccess($ret, CodeResponse::UPDATED_FAIL);
    }
}